var express = require('express');
var router = express.Router();
// PizZip is required because docx/pptx/xlsx files are all zipped files, and
// the PizZip library allows us to load the file in memory
const PizZip = require("pizzip");
const Docxtemplater = require("docxtemplater");
const fs = require("fs");
const path = require('path')
const { v4: uuidv4 } = require("uuid")
const log4js = require("../utils/log")
const wordLogger = log4js.getLogger('word')
const { successRes, errorRes } = require("../utils/response")

router.post('/stay_winter', async function (req, res, next) {
    try {
        let { start_date,end_date,reason,parentAgree,stayAddress,name,sex,college,clazz,studentId,phone,homePhone,homeAddress } = req.body
        // Load the docx file as binary content
        const content = fs.readFileSync(
            path.resolve(__dirname, "../public/file_models/stay_winter.docx"),
            "binary"
        );
        // Unzip the content of the file
        const zip = new PizZip(content);
        // This will parse the template, and will throw an error if the template is
        // invalid, for example, if the template is "{user" (no closing tag)
        const doc = new Docxtemplater(zip, {
            paragraphLoop: true,
            linebreaks: true,
        });
        // Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
        doc.render({
            name: name,
            sex: sex,
            college: college,
            clazz: clazz,
            phone: phone,
            start_date: timestampToTime(parseInt(start_date)),
            end_date: timestampToTime(parseInt(end_date)),
            homePhone: homePhone,
            homeAddress: homeAddress,
            studentId: studentId,
            stayAddress: stayAddress,
            parentAgree:parentAgree,
            reason: reason,
            submitTime: timestampToTime(new Date())
        });
        // Get the zip document and generate it as a nodebuffer
        const buf = doc.getZip().generate({
            type: "nodebuffer",
            // compression: DEFLATE adds a compression step.
            // For a 50MB output document, expect 500ms additional CPU time
            compression: "DEFLATE",
        });
        // buf is a nodejs Buffer, you can either write it to a
        // file or res.send it with express for example.
        const id = uuidv4()
        fs.writeFileSync(path.resolve(__dirname, `../public/files/stay_winter_files/寒假留校申请${id}.docx`), buf);
        const size = await new Promise((resolve, reject) => {
            fs.stat(path.resolve(__dirname, `../public/files/stay_winter_files/寒假留校申请${id}.docx`), (err, stats) => {
                if (err) {
                    reject(err)
                    //一旦reject就会进入捕获阶段 后面的catch就会捕获reject reject的值不会作为await的返回值
                } else {
                    resolve(stats.size)
                }
            });
        })
        successRes(res, '请求成功', `https://www.zyxnbplus.top/getWord/stay_winter/寒假留校申请${id}.docx`)
    } catch (err) {
        console.log(err)
        wordLogger.error(err)
        errorRes(res,'服务端错误')
    }

});
function timestampToTime(timestamp) {
    timestamp = timestamp ? timestamp : null;
    let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '年';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日';
    return Y + M + D;
}



module.exports = router;
